package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import commands.Action;
import commands.AddAction;
import commands.DeleteAction;
import commands.EchoAction;
import commands.NoAction;
import commands.ReadAction;
import commands.WriteAction;

public class Parser {


	public Parser(Subject sub, PrintWriter pw, BufferedReader br)
			throws IOException {
		boolean connected = true;
		while (connected) {
			String line = br.readLine();
			if (line != null) {
				String[] split = line.split(" ", 2);
				Action action = new NoAction(pw);
				System.out.println(split[0]);
				if ("echo".equals(split[0])) {
					action = new EchoAction(pw, split[1]);
				} else if ("logoff".equals(split[0])) {
					connected = false;
					action = new EchoAction(pw, "Sad to see you leave...");
				} else if ("read".equals(split[0])) {
					action = new ReadAction(pw, sub, split[1]);
				}
				else if("add".equals(split[0])){
					action = new AddAction(pw, sub, split[1]);
				}
				else if("delete".equals(split[0])){
					action = new DeleteAction(pw, sub, split[1]);
				}
				else if("write".equals(split[0])){
					action = new WriteAction(pw, sub, split[1]);
				}
				action.perform();
				pw.flush();
			}
		}
	}

}
